package cn.tianyigps.tianyigpsguazi.dao;

import cn.tianyigps.tianyigpspublic.bean.EquipmentModel;
import cn.tianyigps.tianyigpspublic.mongo.dao.BaseDaoImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created with IDEA
 *
 * @description: 设备dao实现
 * @author: cui.guibin
 * @create: 2019/3/20 13:46
 **/
@Repository
public class EquipmentDaoImpl extends BaseDaoImp<EquipmentModel> implements EquipmentDao   {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public List<EquipmentModel> listEquipmentCheckModelById(String equipmentId, Date start, Date end, String collectionName) {

        Criteria criteria = Criteria.where("equipmentId").is(equipmentId);
        if (Optional.ofNullable(start).isPresent() && Optional.ofNullable(end).isPresent()) {
            criteria.and("locateTime").gte(start).lte(end);
        } else if (!Optional.ofNullable(start).isPresent() && Optional.ofNullable(end).isPresent()) {
            criteria.and("locateTime").lte(end);
        } else if (Optional.ofNullable(start).isPresent() && !Optional.ofNullable(end).isPresent()) {
            criteria.and("locateTime").gte(start);
        }
//        if (start != null && end != null)
//            criteria.and("reportTime").gte(start).lte(end);
        Query query = new Query(criteria).with(new Sort(Sort.Direction.ASC, "locateTime"));
        List<EquipmentModel> equipmentCheckModels = mongoTemplate.find(query, getClz(), collectionName);

        if (!equipmentCheckModels.isEmpty()) {
            equipmentCheckModels = equipmentCheckModels.stream().filter(equipmentCheckModel -> (Optional.ofNullable(equipmentCheckModel.getGpsLongitude()).isPresent() && Optional.ofNullable(equipmentCheckModel.getGpsLongitude()).isPresent())).collect(Collectors.toList());
        }
        return equipmentCheckModels;
    }
}
